package 多线程初阶.示例测试;

/**
 * 中断线程:Thread.interrupted() 或者 Thread.currentThread().isInterrupted() 代替自定义标志位
 */
public class TestDemo5 {
    private static class MyRunnable implements Runnable{
    @Override
    public void run() {
      // while (!Thread.interrupted()){  这是清除标志位的写法,可以理解为一个按钮
        while(!Thread.currentThread().isInterrupted()){//这样写更优也更常见
            System.out.println(Thread.currentThread().getName()+" is run");
            try {
                Thread.sleep(1*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread().getName()+" get notice");
                break;
            }
        }
        System.out.println(Thread.currentThread().getName()+" will die");
    }
}

    public static void main(String[] args) throws InterruptedException {
        MyRunnable target=new MyRunnable();
        Thread thread=new Thread(target,"MyThread");
        System.out.println(Thread.currentThread().getName()+" is run");
        thread.start();
        Thread.sleep(10*1000);
        System.out.println(Thread.currentThread().getName()+" post notice");
        thread.interrupt();//中断
        thread.join();//等待线程结束
        /**
         * interrupt方法:
         * ①如果要中断的线程处于阻塞状态,则走异常
         * ②如果未处于阻塞状态,则改变标记位,跳出循环
         * 这种方式通知收到的更及时，即使线程正在 sleep 也可以马上收到
         */
        System.out.println(Thread.currentThread().getName()+" will die");
    }
}
